package com.ym.utils;



import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 *
 * @author: likang
 * @date: 2020/1/8 14:15
 * @description: 获取百度TOKEN
 */
@Component
public class GetTon {


	public static String authHost;
	public static String APIKEY;
	public static String SECRETKEY;

	@Value("${myj.baidu.authHost}")
	public void setAuthHost(String authHost) {
		GetTon.authHost = authHost;
	}

	@Value("${myj.baidu.APIKEY}")
	public void setAPIKEY(String APIKEY) {
		GetTon.APIKEY = APIKEY;
	}

	@Value("${myj.baidu.SECRETKEY}")
	public void setSECRETKEY(String SECRETKEY) {
		GetTon.SECRETKEY = SECRETKEY;
	}

	public static String getToken() {
		BufferedReader br = null;
		StringBuffer sb = new StringBuffer();
  		String getAccessTokenUrl = authHost
				+ "grant_type=client_credentials"
				+ "&client_id=" + APIKEY
				+ "&client_secret=" + SECRETKEY;
		try {
			URL url = new URL(getAccessTokenUrl);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setRequestMethod("POST");
			connection.connect();
			br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String line = "";
			while ((line = br.readLine()) != null) {
				sb.append(line);
			}
			br.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		JSONObject jsonObject = JSONObject.fromObject(sb.toString());
		String token = jsonObject.getString("access_token");
		return token;
	}

	public static void main(String[] args) {
		String tonken = getToken();
		System.out.println(tonken);
	}
}
